<?php

/**
 * ECSHOP 手机抽奖板块
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: category.php 17217 2011-01-19 06:29:08Z liubo $
*/

define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');

/*获取折扣卷*/

if ($_REQUEST['act'] == 'get_discount') {
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $user_id = !empty($_SESSION['user_id'])?$_SESSION['user_id']:'';
    $time = time();
    $return=array('error'=>0,'message'=>'','content'=>'');

    if (empty($user_id)) {
      $return['error']=1;
      $return['message']='请登录后再领取';
      echo $json->encode($return);
      exit();
    }
    /*查询用户是否有抽奖机会*/
    $sql = "SELECT draw_num FROM".$ecs->table('users')." WHERE draw_num > 0 AND user_id = $user_id";
    $draw_num = $db->getOne($sql);
    if (empty($draw_num)) {
      $return['error']=1;
      $return['message']='你没有抽奖机会';
      echo $json->encode($return);
      exit();
    }
    /*查询折扣卷是否还有*/
    $sql =  " SELECT c.coupon_id FROM ".$ecs->table('coupon_type')." AS ct".
            " LEFT JOIN ".$ecs->table('coupon')." AS c ON c.type_id = ct.type_id".
            " WHERE ct.type_code ='discount' AND c.user_id = 0 AND $time > c.get_start_time AND $time < c.get_end_time";
    $coupon_id = $db->getOne($sql);

    if (empty($coupon_id)) {
      $return['error']=1;
      $return['message']='领取完毕';
      echo $json->encode($return);
      exit();
    }
    /*领取折扣卷*/
    $sql = "UPDATE ".$ecs->table('coupon')." SET user_id = '$user_id',is_exchange = 1,exchange_time = '$time' WHERE coupon_id='$coupon_id'";
    $db->query($sql);
    $sql = "UPDATE ".$ecs->table('users')." SET draw_num = (draw_num - 1) WHERE user_id='$user_id'";
    $db->query($sql);
    $return['error']=0;
    $return['message']="领取成功";
    echo $json->encode($return);
    exit();
}
if (empty($_SESSION['user_id'])) {
        ecs_header("Location: index.php\n");
        exit;
}else{
    $user_id=$_SESSION['user_id'];
}
/*查询用户是否有抽奖机会*/

$sql = "SELECT draw_num FROM".$ecs->table('users')." WHERE draw_num > 0 AND user_id = $user_id";
$draw_num = $db->getOne($sql);

if (empty($draw_num)) {
    ecs_header("Location: index.php\n");
    exit;
}








$smarty->assign('position', $position);
$smarty->assign('top_title', "抽奖");
$smarty->display('luck_draw.dwt');

?>
